package com.finance.cooperate.feature.service.impl;

import com.finance.cooperate.common.utils.StringUtil;
import com.finance.cooperate.dao.entity.primary.Device;
import com.finance.cooperate.dao.local.scope.CooperateRequestScope;
import com.finance.cooperate.dao.repository.primary.DeviceRepository;
import com.finance.cooperate.dao.repository.primary.UserRepository;
import com.finance.cooperate.feature.dto.DeviceDTO;
import com.finance.cooperate.feature.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CooperateRequestScope requestScope;

    @Override
    public DeviceDTO getInfo(String uid) {

        DeviceDTO dto = new DeviceDTO();

        Date lastSubmitTime = requestScope.getLastSubmitTime();
        String deviceId = requestScope.getDeviceId();

        List<Device> deviceList = deviceRepository.getDevice(uid, deviceId, lastSubmitTime);

        if (deviceList.size() > 0) {

            Device device = deviceList.get(0);

            dto.setDeviceBrand(device.getDeviceBrand());
            dto.setOperator(device.getOperator());
            dto.setTimeZone(device.getTimeZone());
            dto.setCountry(device.getCountry());
            dto.setNetworkType(device.getNetworkType());
            dto.setMacAddressIsBlank(!StringUtil.isEmptyOrNvl(device.getMacAddress()) ? 1 : 0);
            dto.setCpuNum(device.getCpuNum());

            String resolution = device.getResolution();
            if (!StringUtil.isEmptyOrNvl(resolution) && resolution.contains("x")) {

                String[] split = resolution.split("x");

                Double width = Double.valueOf(split[0]);
                Double height = Double.valueOf(split[1]);

                dto.setResolutionTotal(width * height);
            }

            dto.setTotalStorageSize(StringUtil.digitalLongExtraction(device.getTotalStorageSize()));
            dto.setCanUseStorageSize(StringUtil.digitalLongExtraction(device.getCanUseStorageSize()));
            dto.setTotalMemorySize(StringUtil.digitalLongExtraction(device.getTotalMemorySize()));
            dto.setSdTotalSize(StringUtil.digitalLongExtraction(device.getSdTotalSize()));
            dto.setSdCanUseSize(StringUtil.digitalLongExtraction(device.getSdCanUseSize()));


        }



        return dto;
    }

    @Override
    public Integer getSameDeviceUidCount(String uid) {

        Integer userCount = userRepository.getSameDeviceUserCount(requestScope.getDeviceId());

        return userCount;
    }
}
